import React, {useEffect, useRef, useState} from 'react';
import type {BadgeProps} from 'antd';
import {Button, Image, Table, Statistic, Row, Col, message, Popover, Modal, Form} from 'antd';
import {
    EditOutlined,
    EllipsisOutlined,
    FullscreenOutlined,
    LikeOutlined,
    PlusOutlined,
    SettingOutlined
} from '@ant-design/icons';
import type {ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import {
    addCollectionLog, addPhoneLog, getAddressBook,
    getAgentCaseList,
    getExtensionLink, getImages,
    getLinkByType,
    getPayLink,
    getPayLinkByType, getRecordOptions, getRelatives, getTodayStats,
    getUsrProfileInfo
} from "@/services/bz/bz-api";
import styles from "./Style.less"

import RcResizeObserver from 'rc-resize-observer';
import {useRequest} from "@@/plugin-request/request";
import ProDescriptions from '@ant-design/pro-descriptions';
import {ModalForm, ProFormRadio, ProFormText, ProFormTextArea} from "@ant-design/pro-form";
// @ts-ignore
const {Divider} = ProCard;

// type Record = {
//     appName: string;
//     originNo: string;
//     name: string;
//     overdueDays: number;
//     followTime: string;
//     mobile: string;
//     collectionNo: string;
//     tradeNo: string;
//     userCode: string;
// };

type CountInfo = {
    totalCount: number;
    completedCount: number;
    completionRate: string;
    unfinishedCount: number;
    target: "70%";

}

type DetailListProps = {
    record: any;
    countInfo: CountInfo;
    profileInfo: any,
    relativesData: any,
    relatives: any,
    callingResults: any,
    tagDataList: any,
    addressList: any,
    showAddress: boolean,
    images: any,
    openAddressData: () => void,
    todayPerformance: any
};

const DetailList: React.FC<DetailListProps> = (props) => {

    const {
        record,
        countInfo,
        profileInfo,
        relativesData,
        relatives,
        callingResults,
        tagDataList,
        addressList,
        showAddress,
        openAddressData,
        images,
        todayPerformance
    } = props;
    if (typeof record.originNo === "undefined") {
        return <div></div>;
    }


    console.log(1111, showAddress);
    const [tagData, setTageData] = useState("");
    const [tagData2, setTageData2] = useState("");
    const [responsive, setResponsive] = useState(false);

    const [payLink, setPayLink] = useState("");
    const [extensionLink, setExtensionLink] = useState("");


    const {run: getLinkPay} = useRequest(getPayLink, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setPayLink(res.link)
        }
    });
    const {run: getLinkExtension} = useRequest(getExtensionLink, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setExtensionLink(res.link)
        }
    });
    const {run: addLog} = useRequest(addCollectionLog, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            console.log("addLog", res);
        }
    });

    const getLinkContent = (link: string) => {
        return (
            <div>
                <br/>
                <p>{link}</p>
                <br/>
            </div>
        );
    };
    const getAmountDetail = (record) => {
        return (
            <div>
                <div>
                    <span>Principal: {record.realCapital}</span>
                    <br/>
                    <span>Interest: {record.interest}</span>
                    <br/>
                    <span>Penalty: {record.lateFee}</span>
                    <br/>
                    <span style={{color: 'red'}}>Unpaid Amount: {record.noRepayAmount}</span>
                    <br/>
                    <span>Paid Amount: {record.paidAmount}</span>
                    <br/>
                    <span>Deduct Amount: {record.deductAmount}</span>
                </div>
            </div>
        );
    };

    const getProfileContent = (key: string) => {
        let res = [];

        profileInfo.map(item => {
            if (item.flag === key)
                res.push(
                    <>
                        <ProDescriptions.Item dataIndex={item.name} label={item.name}>
                            {item.value}
                        </ProDescriptions.Item>
                    </>
                )
        })


        return res;
    }

    const tagResults1 = () => {

        const res = [];
        tagDataList.map(item => {
            res.push({
                label: item.name,
                value: item.value,
            })
        })
        return res;
    }


    const [clForm] = Form.useForm();
    const billDetailColums = [
        {
            title: 'Bill Day',
            dataIndex: 'repaymentDate',
            key: 'repaymentDate',
        },
        {
            title: 'Total Money',
            // dataIndex: 'expireAmount',
            key: 'expireAmount',
            render: (record) => {
                return <>
                    <div style={{float: "left"}}>
                        <Popover content={getAmountDetail(record)} trigger="click">
                            <Button type="primary" ghost>
                                {record.expireAmount}
                            </Button>
                        </Popover>
                    </div>
                </>
            }

        },
        {
            title: 'Remain money',
            dataIndex: 'noRepayAmount',
            key: 'noRepayAmount',
            render: text => <a style={{color: "red"}}>{text}</a>,
        },
        {
            title: 'Links',
            key: 'links',
            render: (r) => {
                return <>
                    <div style={{float: "left"}}>
                        <Popover content={getLinkContent(payLink)} trigger="click">
                            <a type="primary" ghost onClick={() => getLinkPay(record.tradeNo)}>
                                pay link
                            </a>
                        </Popover>
                        /
                        <Popover content={getLinkContent(extensionLink)} trigger="click">
                            <a type="primary" danger ghost style={{marginLeft: 3}}
                                    onClick={() => getLinkExtension(record.tradeNo)}>
                                extension link
                            </a>
                        </Popover>

                    </div>
                </>
            }
        }
        ,
        {
            title: 'Action',
            key: 'links2',
            render: (r) => {
                return <>
                    <ModalForm<{
                        CollectionRes: string;
                        CollectionResMore: string;
                    }>
                        form={clForm}
                        trigger={
                            <Button type="primary" style={{marginLeft: 3, float: "left"}} danger={true}>
                                <PlusOutlined/>
                                Record
                            </Button>
                        }
                        autoFocusFirstInput
                        modalProps={{
                            destroyOnClose: true
                        }}
                        onFinish={async (values) => {
                            // const values1 = await clForm.validateFields();
                            const params = {
                                collectionNo: record.collectionNo,
                                content: "[" + tagData + "]",
                                followId: record.followId,
                                followUp: record.followUp,
                                mobile: record.mobile,
                                name: record.name,
                                tradeNo: record.tradeNo,
                                type: values.CollectionRes,
                                userCode: record.userCode
                            }

                            addLog(params)
                            console.log(params);
                            message.success("success");
                            return true;
                        }}
                    >

                        <ProFormRadio.Group
                            options={tagResults1()}
                            name="CollectionRes"
                            label="Collection Result : "
                            radioType="button"
                            fieldProps={{
                                onChange: (e) => {
                                    setTageData("[" + e.target.label + "]");
                                },
                            }}
                            rules={[{required: true, message: 'need select!'}]}
                        />

                        <ProFormTextArea
                            name="CollectionResMore"
                            label="more info:"
                            placeholder="input more details"
                            fieldProps={{
                                value: tagData
                            }}
                        />
                    </ModalForm>

                </>
            }
        }
    ];


    const callingResults1 = () => {

        const res = [];
        callingResults.map(item => {
            res.push({
                label: item.name,
                value: item.value,
            })
        })
        return res;
    }
    const relationsOption1 = () => {

        const res = [];
        relatives.map(item => {
            res.push({
                label: item.name,
                value: item.value,
            })
        })

        return res;
    }

    const relativesColums = [
        {
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
            copyable:true
        },
        {
            title: 'Relation',
            dataIndex: 'relation',
            key: 'relation'
        },
        {
            title: 'Mobile',
            dataIndex: 'mobile',
            key: 'mobile',
            copyable: true,
        },
        {
            title: 'Remark',
            dataIndex: 'collectionContactRecord',
            key: 'collectionContactRecord'
        },
        {
            title: 'Action',
            key: 'action',
            render: (re) => {

                return <>

                    <ModalForm<{
                        callResult: string;
                        callRelation: string;
                    }>
                        trigger={
                            <Button type="primary">
                                <PlusOutlined/>
                                Add Record
                            </Button>
                        }
                        autoFocusFirstInput
                        modalProps={{
                            destroyOnClose: true
                        }}
                        onFinish={async (values) => {
                            const params: BZAPI.AddCallLog = {
                                collectionNo: record.collectionNo,
                                content: "[" + tagData2 + "]",
                                followId: record.followId,
                                followUp: record.followUp,
                                mobile: re.mobile,
                                name: re.name,
                                callingResult: values.callResult,
                                relation: values.callRelation
                            }

                            await addPhoneLog(params);
                            message.success('提交成功');
                            return true;
                        }}
                    >

                        <ProFormRadio.Group
                            options={callingResults1()}
                            name="callResult"
                            label="Calling Result : "
                            radioType="button"
                            rules={[{required: true, message: 'need select!'}]}
                            fieldProps={{
                                onChange: (e) => {
                                    setTageData2("[" + e.target.label + "]");
                                },
                            }}
                        />


                        <ProFormRadio.Group
                            options={relationsOption1()}
                            name="callRelation"
                            label="Relation : "
                            radioType="button"
                            rules={[{required: true, message: 'need select!'}]}
                        />

                        <ProFormTextArea
                            name="callDetail"
                            label="more info:"
                            placeholder="input more details"
                            fieldProps={{
                                value: tagData2
                            }}
                        />
                    </ModalForm>
                </>
            }
        }
    ];

    const addressColums = [
        {
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
            copyable:true
        },
        {
            title: 'Mobile',
            dataIndex: 'mobile',
            key: 'mobile',
            copyable:true
        },
        {
            title: 'Remark',
            dataIndex: 'collectionContactRecord',
            key: 'collectionContactRecord'
        },
        {
            title: 'Last Call',
            dataIndex: 'lastCallTime',
            key: 'lastCallTime'
        },
        {
            title: 'Action',
            key: 'action',
            render: (re) => {

                return <>

                    <ModalForm<{
                        callResult: string;
                        callRelation: string;
                    }>
                        trigger={
                            <Button type="primary" danger={true}>
                                <PlusOutlined/>
                                Add Record
                            </Button>
                        }
                        autoFocusFirstInput
                        modalProps={{
                            destroyOnClose: true
                        }}
                        onFinish={async (values) => {
                            const params: BZAPI.AddCallLog = {
                                collectionNo: record.collectionNo,
                                content: "[" + tagData2 + "]",
                                followId: record.followId,
                                followUp: record.followUp,
                                mobile: re.mobile,
                                name: re.name,
                                callingResult: values.callResult,
                                relation: values.callRelation
                            }

                            await addPhoneLog(params);
                            message.success('提交成功');
                            return true;
                        }}
                    >

                        <ProFormRadio.Group
                            options={callingResults1()}
                            name="callResult"
                            label="Calling Result : "
                            radioType="button"
                            rules={[{required: true, message: 'need select!'}]}
                            fieldProps={{
                                onChange: (e) => {
                                    setTageData2("[" + e.target.label + "]");
                                },
                            }}
                        />


                        <ProFormRadio.Group
                            options={relationsOption1()}
                            name="callRelation"
                            label="Relation : "
                            radioType="button"
                            rules={[{required: true, message: 'need select!'}]}
                        />

                        <ProFormTextArea
                            name="callDetail"
                            label="more info:"
                            placeholder="input more details"
                            fieldProps={{
                                value: tagData2
                            }}
                        />
                    </ModalForm>
                </>
            }
        }
    ];


    console.log(88888, showAddress);
    // setShowAddress(false)
    return (
        <>
            <RcResizeObserver
                key="resize-observer"
                onResize={(offset) => {
                    setResponsive(offset.width < 596);
                }}
            >
                <ProCard.Group title="Target Today" direction={responsive ? 'column' : 'row'}>
                    <ProCard>
                        <Statistic title="TotalCases" value={todayPerformance.total}/>
                    </ProCard>
                    <Divider type={responsive ? 'horizontal' : 'vertical'}/>
                    <ProCard>
                        <Statistic title="PaidCases" value={todayPerformance.finish}/>
                    </ProCard>
                    <Divider type={responsive ? 'horizontal' : 'vertical'}/>
                    <ProCard>
                        <Statistic title="PaidPercent" valueStyle={{color: '#3f8600'}}
                                   value={todayPerformance.paidPercent}/>
                    </ProCard>
                    <Divider type={responsive ? 'horizontal' : 'vertical'}/>
                    <ProCard>
                        <Statistic title="Target" valueStyle={{color: 'red'}} value={todayPerformance.target}/>
                    </ProCard>

                    <ProCard>
                        <Statistic title="Bonus" value={"--"}/>
                    </ProCard>

                </ProCard.Group>
            </RcResizeObserver>
            <ProCard bodyStyle={{padding: 0, overflow: 'auto'}}
                     size="small"
                     tabs={{
                         type: 'card',
                     }}
            >
                <ProCard.TabPane key="tab1" tab="Bill Detail">
                    <Table pagination={false} columns={billDetailColums}
                           dataSource={record.collectionOrderDetailVoList}/>
                </ProCard.TabPane>
                <ProCard.TabPane key="tab2" tab="User Profile">
                    <ProDescriptions title={"information"}>
                        {getProfileContent("information")}
                    </ProDescriptions>
                    <ProDescriptions title={"Basic"}>
                        {getProfileContent("basic")}
                    </ProDescriptions>
                </ProCard.TabPane>
                <ProCard.TabPane key="tab22" tab="Address Book">
                    <div style={{overflow: "auto", maxHeight: 400}}>
                        {showAddress ? <ProTable pagination={false} columns={addressColums}
                                              dataSource={addressList}
                                                 search={false}
                                                 toolBarRender={false}
                            /> :
                            <ProCard
                                layout="center"
                            >
                                <Button type="primary" ghost onClick={() => {
                                    console.log(1231);
                                    openAddressData();
                                }
                                }>
                                    <FullscreenOutlined/>
                                    Expand data
                                </Button>
                            </ProCard>
                        }

                    </div>
                </ProCard.TabPane>
            </ProCard>

            <ProCard bodyStyle={{padding: 0, overflow: 'auto'}}
                     tabs={{
                         type: 'card',
                     }}
            >
                <ProCard.TabPane key="tab11" tab="Relatives">
                    <ProTable pagination={false} columns={relativesColums}
                              dataSource={relativesData}
                              search={false}
                              toolBarRender={false}
                    />
                </ProCard.TabPane>
            </ProCard>
            <ProCard bodyStyle={{padding: 10, overflow: 'auto'}}
                     title={"Images"}
            >
                <Image.PreviewGroup>
                    {images.map(imgUrl => {
                        return <Image width={200} src={imgUrl}/>
                    })}

                </Image.PreviewGroup>
            </ProCard>

        </>
    );
};


type IPListProps = {
    onChange: (record: any) => void;
    setCountInfo: (dt: any) => void;
    originNo: string;
    record: any;
};

const IPList: React.FC<IPListProps> = (props) => {
    const {onChange, originNo, setCountInfo} = props;
    const columns: ProColumns<Record>[] = [

        {
            title: 'PaidStatus',
            key: 'workTaskStatus',
            hideInTable: true,
            initialValue: "doing",
            valueEnum: {
                doing: {text: "unpaid"},
                completed: {text: "paid"}
            },
        },

        {
            title: 'AppName',
            key: 'appName',
            dataIndex: 'appName',
            hideInSearch: true,
        },
        {
            title: 'LoanId',
            key: 'originNo',
            dataIndex: 'originNo',
            copyable:true
        },
        {
            title: 'Status',
            key: 'collectionStatus',
            hideInTable: true,
            valueEnum: {
                104: {text: "PTP"},
                105: {text: "Pay Later"},
                106: {text: "paid"},
                107: {text: "LM"},
                108: {text: "CB"},
                109: {text: "RTP"},
                110: {text: "RNR"},
            },
        },
        {
            title: 'mobile',
            key: 'mobile',
            hideInTable: true,
            dataIndex: 'mobile',
        },
        {
            title: 'UserName',
            key: 'name',
            dataIndex: 'name',
            hideInSearch: true,
        },
        {
            title: 'DueDays',
            key: 'overdueDays',
            dataIndex: 'overdueDays',
            hideInTable: true
        },
        {
            title: 'DueDays/Amount',
            render: (record) => {
                return <div>
                    <span>{record.overdueDays}</span> / <span style={{color: "red"}}>{record.noRepayAmount}</span>
                </div>
            }
        },
        {
            title: 'LastFollowTime',
            key: 'followTime',
            hideInSearch: true,
            dataIndex: 'followTime',
        },
    ];
    return (
        <ProTable<Record>
            columns={columns}
            request={async (params: any) => {
                // 表单搜索项会从 params 传入，传递给后端接口。
                var date = new Date();
                var seperator1 = "-";
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = year + seperator1 + month + seperator1 + strDate;

                let request = {
                    page: params.current,
                    pageSize: params.pageSize,
                    startDate: currentdate,
                    endDate: currentdate,
                    workTaskStatus: "doing",
                }

                if (typeof params.sort !== "undefined") {
                    request.sort = params.sort;
                }

                if (typeof params.workTaskStatus !== "undefined") {
                    request.workTaskStatus = params.workTaskStatus;
                }
                if (typeof params.collectionStatus !== "undefined") {
                    request.collectionStatus = params.collectionStatus;
                }
                if (typeof params.originNo !== "undefined") {
                    request.tradeNo = params.originNo;
                }

                if (typeof params.mobile !== "undefined") {
                    request.mobile = params.mobile;
                }
                if (typeof params.overdueDays !== "undefined") {
                    request.overdueDays = params.overdueDays;
                }

                const response = await getAgentCaseList(request);

                let {data: {itemList, countInfo}, page: {totalCount}} = response;
                setCountInfo(countInfo);
                const firstRecord = itemList[0];
                onChange(firstRecord);
                return {data: itemList, success: true, total: totalCount}
            }}
            rowClassName={(record) => {
                return record.originNo === originNo ? styles.clickRowStyl : ''
            }}
            rowKey="originNo"
            options={false}
            size={"small"}
            onRow={(record) => {
                return {
                    onClick: () => {
                        onChange(record)
                    },
                };
            }}
            // pagination={}
        />
    );
};

const CaseList: React.FC = () => {
    const [record, setRecord] = useState({});
    const [countInfo, setCountInfo] = useState({});
    const [profileInfo, setProfileInfo] = useState([]);

    const {run: getProfile} = useRequest(getUsrProfileInfo, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setProfileInfo(res.list)
        }
    });

    const [relativesData, setRelativesData] = useState([]);
    const [familyOpetion, setFamilyOption] = useState([]);
    const [friendOption, setFriendOption] = useState([]);
    const [callingResults, setCallingResults] = useState([]);
    const [relatives, setRelatives] = useState([]);
    const [tagDataList, settagDataList] = useState([]);
    const [addressList, setAddressList] = useState([]);
    const [showAddress, setShowAddress] = useState(false);
    const [images, setImages] = useState([]);
    const [todayPData, setTodayPData] = useState([]);

    const {run: getRelativesList} = useRequest(getRelatives, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setRelativesData(res.contacts)
            setFamilyOption(res.familyContactTypeOptions)
            setFriendOption(res.friendContactTypeOptions)
        }
    });
    const {run: getOptions} = useRequest(getRecordOptions, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setRelatives(res.relatives)
            setCallingResults(res.callingResults)
            settagDataList(res.tagDataList)
        }
    });


    const {run: getAddress} = useRequest(getAddressBook, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setAddressList(res.list)
        }
    });
    const {run: todayP} = useRequest(getTodayStats, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setTodayPData(res.todayAdminPerformace[0])
        }
    });

    const {run: getImg} = useRequest(getImages, {
        manual: true,
        throttleInterval: 2000,
        onSuccess: (res) => {
            setImages(res.list)
        }
    });


    return (
        <ProCard split="vertical">
            <ProCard bodyStyle={{padding: 0, overflow: 'auto'}}>
                <IPList
                    onChange={(record1) => {
                        setRecord(record1);
                        getProfile({tradeNo: record1.tradeNo})
                        getRelativesList({tradeNo: record1.tradeNo})
                        getOptions({});
                        getAddress({tradeNo: record1.tradeNo})
                        getImg({collectionNo: record1.collectionNo})
                        setShowAddress(false);
                        todayP({});
                    }}
                    originNo={record.originNo}
                    setCountInfo={(countInfo1) => {
                        setCountInfo(countInfo1)
                    }}/>
            </ProCard>
            <ProCard bodyStyle={{padding: 0, overflow: 'auto'}}>
                <DetailList record={record}
                            countInfo={countInfo} profileInfo={profileInfo}
                            relativesData={relativesData}
                            relatives={relatives}
                            callingResults={callingResults}
                            tagDataList={tagDataList}
                            addressList={addressList}
                            showAddress={showAddress}
                            openAddressData={() => {
                                console.log(showAddress);
                                setShowAddress(true);
                            }}
                            images={images}
                            todayPerformance={todayPData}
                />
            </ProCard>
        </ProCard>
    );
};

export default CaseList;